package midd

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go-member/controller/common"
	"go-member/db"
	"go-member/tool"
)

// CheckLogin
// @Description: 校验是否登录
// @return gin.HandlerFunc
func CheckLogin() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		token := ctx.Request.Header.Get("token")
		if token == "" {
			common.ErrorBadRequest(ctx, "缺少关键数据Token")
			ctx.Abort()
			return
		}
		_, err := tool.DecryptByAes(token, tool.CommonKey)
		if err != nil {
			fmt.Println(err)
			common.ErrorBadRequest(ctx, "Token错误")
			ctx.Abort()
			return
		}

		redis := db.InitRedis()
		token = fmt.Sprintf("auth:%s", token)
		result, err := redis.Get(ctx, token).Result()
		if err != nil || result == "" {
			common.ErrorBadUnauthorized(ctx)
			ctx.Abort()
			return
		}
		ctx.Next()

	}
}
